from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from rest_framework.views import APIView
from rest_framework.versioning import QueryParameterVersioning, URLPathVersioning

from .models import Students, StudentsToken
from .serializers import StudentsSerializer

from utils import utils
# Create your views here.


# class StudentsAPIView(APIView):
#
#     def get(self, request, *args,**kwargs):
#         pass
#
#     def post(self, request, *args, **kwargs):
#         ret = {"code": 10000, "msg": None, "code": None}
#         try:
#             data = request.query_params.dict()
#             username = data['name']
#             userage = data['age']
#             obj = Students.studentsmanger.filter(name=username, age=userage).first()
#             if not obj:
#                 ret["code"] = 10001
#                 ret["msg"] = "nameage错误"
#             token = utils.md5(username)
#             print(token)
#             # tokenobj = StudentsToken.tokenmanger.filter(studentsid=obj).first()
#             # print(tokenobj)
#             # if tokenobj:
#             #     StudentsToken.tokenmanger.update(token=token)
#             #     ret["token"] = token
#             # else:
#             #     studentstoken = StudentsToken.tokenmanger.create(studentsid=obj, token=token)
#             #     studentstoken.save()
#             #     ret["token"] = token
#             ret["token"] = token
#             StudentsToken.tokenmanger.update_or_create(studentsid=obj, defaults={'token': token})
#         except:
#             ret["code"] = 10001
#             ret["msg"] = "name或者age错误"
#         return JsonResponse(ret)


class StudentsAPIView(APIView):


    serializer_class = StudentsSerializer

    def get(self, request, *args,**kwargs):
        queryset = Students.studentsmanger.all()
        data = [num for num in queryset]
        return HttpResponse(queryset)

    def post(self, request, *args, **kwargs):
        import time
        from random import randint
        ret = {"code": 10000, "msg": "获取验证码成功", "username": request.data["username"], "messcode": randint(1000, 9999), "token": int(time.time())}
        return JsonResponse(ret)
